package com.biz.aoao.mysql.mysqlbinlogsync.extra;

import com.biz.aoao.mysql.mysqlbinlogsync.config.MySqlHost;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;


@Slf4j
public class DbUtils {

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static String[] getColumns(MySqlHost host, String db, String table) {
        ResultSet resultSet =null;
        Statement statement = null;
        Connection connection =null;
        try {
            String url =  "jdbc:mysql://" + host.getHost()+":" +host.getPort()+
                    "/INFORMATION_SCHEMA?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
            connection  = DriverManager.getConnection(url, host.getUsername(), host.getPassword());
            statement = connection.createStatement();

            String sql = "select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='"
                    + db + "' and TABLE_NAME='" + table + "' order by ORDINAL_POSITION asc;";

            resultSet = statement.executeQuery(sql);
            List<String> buf = new ArrayList<>();

            while (resultSet.next()) {
                buf.add(resultSet.getString(1));
            }

            return buf.toArray(new String[0]);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                   log.error("close reseutlSet error",e);
                }
            }

            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    log.error("close statement error",e);
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    log.error("close connection error",e);
                }
            }
        }
    }
}
